from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                               QPushButton, QLabel, QStackedWidget, QFrame)
from PySide6.QtCore import Qt, QSize
from PySide6.QtGui import QFont, QIcon
from views.pages.member_page import MemberPage
from views.pages.appointment_page import AppointmentPage
from views.pages.service_page import ServicePage
from views.pages.staff_page import StaffPage
from views.pages.payment_page import PaymentPage
from views.pages.report_page import ReportPage
from views.pages.settings_page import SettingsPage


class MainWindow(QMainWindow):
    def __init__(self, current_user):
        super().__init__()
        self.current_user = current_user
        self.pages = []  # 存储所有页面
        self.setup_ui()
        self.apply_styles()

    def setup_ui(self):
        self.setWindowTitle("理发店管理系统")
        self.setWindowIcon(QIcon("assets/dialog_icon.svg"))
        self.setMinimumSize(1200, 800)

        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 主布局
        main_layout = QHBoxLayout(central_widget)
        main_layout.setSpacing(0)
        main_layout.setContentsMargins(0, 0, 0, 0)

        # 左侧菜单
        self.setup_left_menu()

        # 右侧内容区
        self.setup_right_content()

        # 添加到主布局
        main_layout.addWidget(self.left_menu)
        main_layout.addWidget(self.right_content)

        # 设置布局比例
        main_layout.setStretch(0, 2)  # 左侧菜单占比
        main_layout.setStretch(1, 8)  # 右侧内容区占比

    def setup_left_menu(self):
        self.left_menu = QFrame()
        self.left_menu.setObjectName("leftMenu")
        self.left_menu.setStyleSheet("""
            #leftMenu {
                background-color: #2c3e50;
                border-right: 1px solid #34495e;
            }
            QLabel {
                color: #ecf0f1;
            }
            #menuButton {
                text-align: left;
                padding: 12px 20px;
                color: #bdc3c7;
                border: none;
                font-size: 14px;
            }
            #menuButton:hover {
                background-color: #34495e;
                color: #ecf0f1;
            }
            #menuButton:checked {
                background-color: #34495e;
                color: #3498db;
                border-left: 4px solid #3498db;
            }
        """)

        layout = QVBoxLayout(self.left_menu)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)

        # 用户信息区
        user_info = QFrame()
        user_info.setObjectName("userInfo")
        user_info.setStyleSheet("""
            #userInfo {
                background-color: #34495e;
                padding: 20px;
                border-bottom: 1px solid #2c3e50;
            }
        """)
        user_layout = QVBoxLayout(user_info)
        user_layout.setSpacing(10)
        user_layout.setContentsMargins(0, 0, 0, 0)

        # 用户头像占位
        avatar = QLabel()
        avatar.setFixedSize(60, 60)
        avatar.setStyleSheet("""
            background-color: #3498db;
            border-radius: 30px;
        """)

        # 用户信息文字
        username_label = QLabel(f"{self.current_user['username']}")
        username_label.setStyleSheet("""
            font-size: 16px;
            font-weight: 500;
            color: #ecf0f1;
        """)

        role_label = QLabel(f"{self.current_user['role']}")
        role_label.setStyleSheet("""
            font-size: 12px;
            color: #bdc3c7;
        """)

        user_layout.addWidget(avatar, 0, Qt.AlignCenter)
        user_layout.addWidget(username_label, 0, Qt.AlignCenter)
        user_layout.addWidget(role_label, 0, Qt.AlignCenter)

        # 菜单按钮
        self.menu_buttons = []
        self.menu_items = [
            ("预约管理", "calendar", AppointmentPage, 0),
            ("服务项目", "services", ServicePage, 1),
            ("员工管理", "staff", StaffPage, 2),
            ("会员管理", "members", MemberPage, 3),
            ("收银结算", "payment", PaymentPage, 4),
            ("统计报表", "reports", ReportPage, 5),
            ("系统设置", "settings", SettingsPage, 6)
        ]

        print(f"Menu items count: {len(self.menu_items)}")  # 添加调试信息

        button_group = QFrame()
        button_layout = QVBoxLayout(button_group)
        button_layout.setSpacing(5)
        button_layout.setContentsMargins(10, 20, 10, 20)

        for text, icon_name, _, index in self.menu_items:
            btn = QPushButton(text)
            btn.setObjectName("menuButton")
            btn.setCheckable(True)
            btn.setCursor(Qt.PointingHandCursor)

            # 设置图标（需要准备图标资源）
            btn.setIcon(QIcon(f"assets/menu_{icon_name}.png"))
            btn.setIconSize(QSize(20, 20))

            btn.clicked.connect(self.create_page_switch_handler(index))
            self.menu_buttons.append(btn)
            button_layout.addWidget(btn)

        # 添加用户信息区和按钮组
        layout.addWidget(user_info)
        layout.addWidget(button_group)
        layout.addStretch()

        # 添加退出按钮
        logout_btn = QPushButton("退出系统")
        logout_btn.setObjectName("logoutButton")
        logout_btn.clicked.connect(self.logout)
        layout.addWidget(logout_btn)

    def create_page_switch_handler(self, index):
        """创建页面切换处理函数"""
        def handler(checked=False):
            self.switch_page(index)
        return handler

    def setup_right_content(self):
        self.right_content = QFrame()
        self.right_content.setObjectName("rightContent")

        layout = QVBoxLayout(self.right_content)
        layout.setContentsMargins(20, 20, 20, 20)

        # 顶部信息栏
        top_bar = QFrame()
        top_bar.setObjectName("topBar")
        top_layout = QHBoxLayout(top_bar)

        self.page_title = QLabel("预约管理")
        self.page_title.setObjectName("contentTitle")

        top_layout.addWidget(self.page_title)
        top_layout.addStretch()

        # 内容区域
        self.content_stack = QStackedWidget()

        # 创建页面类列表
        page_classes = [
            (AppointmentPage, "预约管理"),
            (MemberPage, "会员管理"),
            (ServicePage, "服务项目"),
            (StaffPage, "员工管理"),
            (PaymentPage, "收银结算"),
            (ReportPage, "统计报表"),
            (SettingsPage, "系统设置")
        ]

        # 创建页面实例
        self.pages = []
        for page_class, title in page_classes:
            try:
                print(f"Creating page: {page_class.__name__}")
                # 检查是否需要传递current_user参数
                if page_class == AppointmentPage:
                    page = page_class(self.current_user)
                else:
                    page = page_class()
                self.content_stack.addWidget(page)
                self.pages.append(page)
            except Exception as e:
                print(f"Error creating page {page_class.__name__}: {str(e)}")
                # 添加空页面作为占位符
                empty_page = QWidget()
                self.content_stack.addWidget(empty_page)
                self.pages.append(empty_page)

        # 设置默认页面
        if self.menu_buttons:
            self.menu_buttons[0].setChecked(True)
            self.content_stack.setCurrentIndex(0)
            self.page_title.setText(self.menu_items[0][0])

        # 添加到布局
        layout.addWidget(top_bar)
        self.right_content.setLayout(QVBoxLayout())
        self.right_content.layout().setContentsMargins(10, 10, 10, 10)
        self.right_content.layout().addWidget(self.content_stack)

    def switch_page(self, index):
        """切换页面"""
        print(f"Switching to page index: {index}")  # 添加调试信息
        try:
            # 更新按钮状态
            for i, btn in enumerate(self.menu_buttons):
                btn.setChecked(i == index)

            # 切换页面
            self.content_stack.setCurrentIndex(index)
            # 更新标题
            self.page_title.setText(self.menu_items[index][0])
            print(f"Successfully switched to page: {self.menu_items[index][0]}")  # 添加调试信息
        except Exception as e:
            print(f"Error switching page: {str(e)}")  # 添加错误信息

    def logout(self):
        """退出系统"""
        from views.auth.login import LoginWindow
        self.login_window = LoginWindow()
        self.login_window.show()
        self.close()

    def apply_styles(self):
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f5f6fa;
            }
            #leftMenu {
                background-color: #2f3542;
                min-width: 200px;
                max-width: 200px;
            }
            #userInfo {
                padding: 20px;
                color: white;
                border-bottom: 1px solid #535c68;
            }
            #menuButton {
                text-align: left;
                padding: 15px 20px;
                border: none;
                color: white;
                background-color: transparent;
                font-size: 14px;
            }
            #menuButton:hover {
                background-color: #3742fa;
            }
            #menuButton:checked {
                background-color: #5352ed;
            }
            #logoutButton {
                text-align: center;
                padding: 15px 20px;
                border: none;
                color: white;
                background-color: #e84118;
                font-size: 14px;
                margin: 10px;
            }
            #logoutButton:hover {
                background-color: #c23616;
            }
            #rightContent {
                background-color: white;
                border-radius: 10px;
                margin: 10px;
            }
            #topBar {
                background-color: transparent;
                border-bottom: 2px solid #f1f2f6;
                padding: 10px;
            }
            #contentTitle {
                font-size: 18px;
                font-weight: bold;
                color: #2f3542;
            }
        """)
